package com.zy.hh.config;
import org.apache.commons.dbcp.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import java.io.IOException;
@Configuration
@ComponentScan(basePackages = "com.zy.hh")
@PropertySource("classpath:jdbc.properties")//引入jdbc配置文件
@MapperScan(basePackages = "com.zy.hh.mapper")
public class ApplicationConfig{
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //配置数据源
    //数据源
    @Bean
    public BasicDataSource dateSource(){
        BasicDataSource dataSource =new BasicDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
// 配置sqlSessionFactoryBean
    @Bean
    @Scope
    public SqlSessionFactoryBean sqlSessionFactoryBean(){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dateSource());
   //解析xml配置文件
        PathMatchingResourcePatternResolver patternResolver=new PathMatchingResourcePatternResolver();
       //引入mybatis核心配置文件
        sqlSessionFactoryBean.setConfigLocation(patternResolver.getResource("classPath:mybatis-config.xml"));
        //sql.xml映射文件   会有多个
        try {
            sqlSessionFactoryBean.setMapperLocations(patternResolver.getResources("classpath:/mapper/*Mapper.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactoryBean;
    }
}
